package chat.server;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import gui.Chat;
import utils.ServerConfig;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;

//单独线程，用于客户端接收服务器发送的聊天信息
public class ServerInPut implements Runnable{
    private int port;
    public ServerInPut(int port){
        this.port=port;
    }

    @Override
    public void run() {
        Socket socket=null;
        InputStream inputStream=null;
        ByteOutputStream byteArrayOutputStream=null;
        try {
            //加入服务器端时会自动连接
            socket = new Socket(InetAddress.getByName(ServerConfig.serverConfigString("InetAddress")),port);
            System.out.println("input以连接");
            while (true){
                if(socket.isClosed()){
                    socket = new Socket(InetAddress.getByName(ServerConfig.serverConfigString("InetAddress")),port);
                }
                inputStream = socket.getInputStream();
                byteArrayOutputStream = new ByteOutputStream();
                byte[] bytes = new byte[1024];
                int len;
                while ((len= inputStream.read(bytes))!=-1){
                    byteArrayOutputStream.write(bytes,0,len);
                }
                byteArrayOutputStream.flush();
                inputStream.close();
                String message=byteArrayOutputStream.toString();
//                String[] split = a.split(",");
//                String username=split[0];
//                String message=split[1];
//                Chat.setUsername(username);
                //System.out.println("input="+message);
                //将聊天信息传至GUI用户界面
                if(!"".equals(message)){
                    Chat.setMessage(message);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                byteArrayOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
